<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item to="/dashboard">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="user-container">
      <el-row>
        <el-col :span="8">
          <!-- 1.添加按钮 -->
          <el-button
            type="success"
            size="mini"
            icon="el-icon-circle-plus-outline"
            @click="handleAdd"
          >
            添加用户
          </el-button>
        </el-col>
      </el-row>
      <!-- 2.数据表格 -->
      <el-table :data="users" border stripe>
        <el-table-column label="id" prop="id"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scoped">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scoped.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scoped.row.id)"
              :plain="true"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 3.分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[2, 5]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加对话框 -->
    <el-dialog
      :title="isEdit ? '修改用户' : '添加用户'"
      :visible.sync="dialogVisible"
    >
      <el-form ref="form" :model="form" :rules="Rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="密　码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="onSubmit">提交</el-button>
          <el-button @click="Cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 删除对话框 -->
    <el-dialog title="删除用户" :visible.sync="isDelete">
      <el-form>
        <el-form-item>是否真要删除该用户?</el-form-item>
        <el-form-item>
          <el-button type="success" @click="del">确定</el-button>
          <el-button @click="Cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'User',
  data() {
    return {
      users: [],
      page: 1, //当前页码
      size: 5, //每页显示记录
      total: 0,
      dialogVisible: false, //对话框开始状态
      form: {
        username: '',
        password: '',
      },
      isDelete: false,
      id: '',
      isEdit: false,
      Rules: {
        username: [
          //不能为空;提示信息;触发,失去焦点的时候
          { required: true, message: '用户名不能为空', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    //调用函数
    this.getUsers()
  },
  methods: {
    getUsers() {
      //获取用户数据方法
      this.$http
        .get(`/users?page=${this.page}&size=${this.size}`)
        .then((data) => {
          //1.更新数组,数组只能传递数组
          this.users = data.result.data
          //2.更新总记录
          this.total = data.result.total
        })
    },
    handleSizeChange(s) {
      this.size = s
      this.getUsers()
    },
    handleCurrentChange(p) {
      this.page = p
      this.getUsers()
    },
    handleAdd() {
      //给form表单中赋为空
      this.form = {}
      //显示对话框,添加状态
      this.dialogVisible = true
      //关闭修改状态
      this.isEdit = false
    },
    onSubmit() {
      //实现表单校验
      this.$refs['form'].validate((valid) => {
        //判断校验,成功发送axios请求
        if (valid) {
          //判断是否编辑,发送修改请求
          if (this.isEdit) {
            // isEdit==true: 修改状态
            // 发送 PUT 请求,
            this.$http.put(`/users/${this.form.id}`, this.form).then((res) => {
              const { code, message } = res
              if (code != 0) {
                // 提示
                this.$message.error(message)
                return
              }
              this.$message({
                type: 'success',
                message: message,
                showClose: true,
                duration: 1000,
              })
              // 1. 关闭对话框
              this.dialogVisible = false
              // 2. 重新获取数据
              this.getUsers()
              // 3. 清空表单
              this.$refs['form'].resetFields()
            })
          } else {
            //否则添加状态,发送post添加请求接口
            this.$http.post('/users', this.form).then((res) => {
              const { code, message } = res
              if (code != 0) {
                // 提示
                this.$message.error(message)
                return
              }
              this.$message({
                type: 'success',
                message: message,
                showClose: true,
                duration: 1000,
              })
              //console.log(res)
              // 1. 关闭对话框
              this.dialogVisible = false
              // 2. 重新获取数据
              this.getUsers()
              // 3. 清空表单
              this.$refs['form'].resetFields()
            })
          }
        }
      })
    },
    Cancel() {
      this.dialogVisible = false
      this.isDelete = false
      // this.form.username = ''
      // this.form.password = ''
    },
    handleDelete(id) {
      //显示删除对话框,添加状态
      this.isDelete = true
      //给user_id赋值
      this.id = id
    },
    del() {
      this.$http.delete(`/users/${this.id}`).then((res) => {
        //console.log(res)
        const { message } = res
        //console.log(message)
        //1.弹出提示框
        this.$message({
          message: message,
          type: 'success',
        })
        //显示删除对话框,添加状态
        this.isDelete = false
        // 重新获取数据
        this.getUsers()
      })
    },
    handleEdit(row) {
      // 更新isEdit状态,编辑状态
      this.isEdit = true
      // 显示对话框
      this.dialogVisible = true
      //数据回显,调用接口
      this.$http.get(`/users/${row.id}`).then((res) => {
        // 根据返回的数据, 更新form状态
        this.form = res.result
      })
    },
  },
}
</script>
<style scoped>
/*
scoped 作用域:
在这写的样式,只影响当前组件
*/
.el-breadcrumb {
  font-size: 20px;
}
.user-container {
  margin-top: 10px;
}
.el-table {
  margin-top: 10px;
}
.el-pagination {
  margin-top: 10px;
}
</style>
